const imageRatio = {
	horizontal: {
		width: 670,
		height: 447
	},
	vertical: {
		width: 670,
		height: 890
	}
};
export default {
	methods: {
		async calc(src) {
			this.$refs.loading.show('生成中');
			const rect = await this.getImageInfo();
			uni.getImageInfo({
				src,
				success: res => {
					const {
						path,
						width: imageWidth,
						height: imageHeight
					} = res;
					this.image.height = (rect.width * imageHeight) / imageWidth;
					this.path = path;
					if (this.isShare) {
						this.type = 'share';
					} else {
						if (imageWidth <= imageHeight) {
							this.type = 'vertical';
						} else {
							this.type = 'horizontal';
						}
					}
					const cType = imageRatio[this.type];
					const width = cType.width / this.ratio;
					const height = cType.height / this.ratio;
					const top = (this.height - height) / 2;
					const left = (this.width - width) / 2;
					Object.assign(this.box, {
						width,
						height,
						top,
						left
					});
				},
				complete: () => {
					this.$refs.loading.hide();
				}
			});
		},
		async confirm(event) {
			this.$refs.loading.show('裁剪中');
			const ctx = uni.createCanvasContext('myCanvas', this);
			const {
				image,
				pixelRatio,
				box,
				path
			} = this;
			const imgW = image.width * image.scale;
			const imgH = image.height * image.scale;
			let dx = (imgW - box.width) / 2 - image.left;
			let dy = (imgH - box.height) / 2 - image.top;
			// ctx.setFillStyle('black');
			// ctx.fillRect(0, 0, box.width * pixelRatio, box.height * pixelRatio);
			ctx.save();
			await ctx.drawImage(path, -dx * pixelRatio, -dy * pixelRatio, imgW * pixelRatio, imgH * pixelRatio);
			ctx.restore();
			ctx.draw(true, () => {
				uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						width: box.width * pixelRatio,
						destWidth: box.width * pixelRatio,
						height: box.height * pixelRatio,
						destHeight: box.height * pixelRatio,
						fileType: 'png',
						success: res => {
							this.$refs.loading.hide();
							this.$emit('update:visible', false);
							this.$emit('confirm', res.tempFilePath);
							this.reset();
						},
						fail: e => {
							console.log(e)
							this.$refs.loading.hide();
							uni.showToast({
								icon: 'none',
								title: '裁剪失败'
							});
						}
					},
					this
				);
			});
		}
	}
}
